package org.pz.config;

import lombok.extern.slf4j.Slf4j;
import org.pz.cllient.UserClient;
import org.pz.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Slf4j
@Configuration
public class SecurityConfig {

    @Autowired
    private UserClient userClient;

    /**
     * 模拟根据用户名设置用户认证信息
     * */
    @Bean
    public UserDetailsService userDetailsServiceByUsername(){
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

                //根据用户名查询一个 User
                UserEntity ud = userClient.findUserInfoByUsername(username);
                String[] authors = new String[]{};
                authors = ud.getRoles().toArray(authors);

                return User.withUsername(ud.getUsername())
                        .password(ud.getPassword())
                        .authorities(authors)
                        .build();
            }
        };
    }

    /**
     * 密码编码器
     * */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

}
